//   
//   MenuView.swift
//   BaseComponetKit
//   Created  by monkey on 2024/4/2
//   
//   
   
import UIKit
import Lottie
protocol MenuViewDelegate: AnyObject {
    func menuView(_ menuView: MenuView, didSelectItemAt index: Int, item: MenuItem)
}

class MenuView: UIView {
    var animationView : LottieView?
    weak var delegate: MenuViewDelegate?
    private var collectionView: UICollectionView!
    private var menuItems: [[NSAttributedString]] = [] // 支持富文本的菜单项数据
    private let itemsPerPage = 15 // 每页显示的菜单项数量
    private let itemSize = CGSize(width: UIScreen.main.bounds.width / 5, height: 80) // 自定义cell大小
    private var pageControl: UIPageControl! // 添加UIPageControl
    var loopMode: LottieLoopMode = .loop

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupMenuItems()
        setupCollectionView()
        setupPageControl() // 调用设置UIPageControl的方法
        
        let imageView = UIImageView()
        if let gifImage = UIImage(named: "your_gif_image") {
            imageView.image = gifImage
        }

        addSubview(imageView)
        imageView.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: 80, height: 80))
            make.center.equalToSuperview()
        }
        setupanimationView()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 设置菜单项的私有函数
    private func setupMenuItems() {
        // 存储每页的菜单项数据
        var pageItems: [NSAttributedString] = []
        for i in 1...MenuItem.allCases.count{
            // 获取当前菜单项的名称
            let menuItemNameIndex = (i - 1) % MenuItem.allCases.count
            let menuItemName = MenuItem.allCases[menuItemNameIndex]

            let attributedString = NSMutableAttributedString(string: "\(menuItemName.rawValue)")
            // 添加富文本菜单项到当前页
            pageItems.append(attributedString)
            // 检查是否达到每页菜单项数量或者已经到了最后一项
            if pageItems.count == itemsPerPage || i == MenuItem.allCases.count {
                // 将当前页菜单项添加到菜单项数组中
                menuItems.append(pageItems)
                // 重置当前页菜单项数组
                pageItems = []
            }
        }
    }

    private func setupCollectionView() {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.itemSize = itemSize // 设置每个cell的大小
        collectionView = UICollectionView(frame: bounds, collectionViewLayout: layout)
        collectionView.backgroundColor = .clear
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.isPagingEnabled = true // 开启分页功能
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.register(MenuItemCell.self, forCellWithReuseIdentifier: "Cell")
        addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.bottom.equalToSuperview().inset(10)
        }
    }
    private func setupPageControl() {
        pageControl = UIPageControl()
        pageControl.isHidden = true
        pageControl.numberOfPages = menuItems.count // 设置初始页面数量
        pageControl.currentPage = 0 // 设置初始当前页面
        pageControl.currentPageIndicatorTintColor = .red
        pageControl.pageIndicatorTintColor = .lightGray
        addSubview(pageControl)
        pageControl.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview() // 调整UIPageControl的位置
            make.height.equalTo(10)
        }
    }
    private func setupanimationView() {
        animationView = LottieView(jsonFileName: "arrowLottie")
        addSubview(animationView!)
        animationView!.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(30)
            make.centerY.equalToSuperview()
            make.size.equalTo(CGSize(width: 80, height: 80))
        }
    }
}

extension MenuView: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return menuItems.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return menuItems[section].count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! MenuItemCell
        cell.backgroundColor = .clear // 调整菜单项的背景颜色
        cell.label.attributedText = menuItems[indexPath.section][indexPath.item]
        let menuItem2 = MenuItem.allCases[indexPath.section * 15 + indexPath.row]
        cell.iconImageView.image = UIImage(named: menuItem2.iconName())
        // 尝试加载菜单项图标，如果失败则使用默认图标
        if let iconImage = UIImage(named: menuItem2.iconName()) {
            if let dominantColor = iconImage.averageColorInCenter() {
                cell.label.textColor = dominantColor
            }
            cell.iconImageView.image = iconImage
            // 获取图标的平均颜色
              
        } else {
            // 加载失败，使用默认图标
            cell.iconImageView.image = UIImage(named: "mune-1")
        }

        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
          let index = indexPath.section * itemsPerPage + indexPath.item
          let selectedItem = MenuItem.allCases[index]
          delegate?.menuView(self, didSelectItemAt: index, item: selectedItem)
    }
}
extension MenuView: UICollectionViewDelegate {
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        var currentPage = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        if (scrollView.contentOffset.x.truncatingRemainder(dividingBy: scrollView.bounds.width)) > 0 {
            currentPage += 1
        }
        pageControl.currentPage = currentPage
        animationView!.isHidden = true
        if currentPage < (menuItems.count - 1){
            animationView!.isHidden = false
        }
     
    }
}


class MenuItemCell: UICollectionViewCell {
    let containerGuide = UILayoutGuide()

    let iconImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = .scaleAspectFit
       // imageView.image = UIImage(named: "mune-1")
        imageView.backgroundColor = .clear
        return imageView
    }()
    
    let label: UILabel = {
        let label = UILabel()
        label.textAlignment = .center
        label.numberOfLines = 0
        label.font = UIFont.systemFont(ofSize: 15, weight: .semibold)
        return label
    }()
    
    let labeltag: UILabel = {
        let label = UILabel()
        label.textAlignment = .center
        label.numberOfLines = 0
        label.font = UIFont.systemFont(ofSize: 15)
        return label
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupSubviews()
      //  contentView.addBorderRecursively()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupSubviews() {
        addLayoutGuide(containerGuide)
        containerGuide.snp.makeConstraints { make in
               make.center.equalToSuperview()
               make.size.equalTo(CGSize(width: 80, height: 65))
        }
        // Add icon image view
        addSubview(iconImageView)
        iconImageView.snp.makeConstraints { make in
            make.top.equalTo(containerGuide).offset(5)
            make.size.equalTo(CGSize(width: 40, height: 40))
            make.centerX.equalTo(containerGuide)

        }
        
        // Add label
        addSubview(label)
        label.snp.makeConstraints { make in
            make.top.equalTo(iconImageView.snp.bottom).offset(5)
            make.width.equalToSuperview()
            make.height.equalTo(20)
        }
        label.snp.makeConstraints { make in
            make.top.equalTo(iconImageView.snp.bottom).offset(5)
            make.width.equalToSuperview()
            make.height.equalTo(20)
        }
        
    }
}


// 定义菜单项枚举
enum MenuItem: String, CaseIterable {
    case care = "护理"
    case sleep = "睡眠"
    case weaning = "辅食"
    case height = "身高"
    case formula = "奶粉"
    case vaccine = "打疫苗"
    case stool = "大便"
    case earlyEducation = "早教"
    case game = "亲子互动"
    case learning = "学习"
    case emotion = "宝宝情绪"
    case social = "社交"
    case milestone = "里程碑"
    case environment = "家庭环境"
    case exercise = "宝宝运动"
    case relationship = "成长关系"
    
    // 获取菜单项对应的图标名称
    func iconName() -> String {
        switch self {
        case .sleep:
            return "home-menu-sleep"
        case .care:
            return "home-menu-care"
        case .weaning:
            return "home-menu-weaning"
        case .height:
            return "home-menu-height"
        case .formula:
            return "home-menu-formula"
        case .vaccine:
            return "home-menu-vaccine"
        case .stool:
            return "home-menu-stool"
        case .earlyEducation:
            return "home-menu-early-education"
        case .game:
            return "home-menu-game"
        case .learning:
            return "home-menu-learning"
        case .emotion:
            return "home-menu-emotion"
        case .social:
            return "home-menu-social"
        case .milestone:
            return "home-menu-milestone"
        case .environment:
            return "home-menu-environment"
        case .exercise:
            return "home-menu-exercise"
        case .relationship:
            return "home-menu-relationship"
        }
    }
}
